﻿using MediatR;
using S.Authorization.Common;
using S.Authorization.Domain.Model.Organization;
using S.Authorization.Infrastructure.Interface.Organization;
using S.Authorization.Read.API.Application.Command.OrganizationCommand;
namespace S.Authorization.Read.API.Application.CommandHandlers.OrganizationCommandHandler
{
    public class ColumnManagementListCommandHandler:IRequestHandler<ColumnManagementListCommand,Pager<ColumnManagementModel>>,IRequestHandler<ColumnManagementById,List<ColumnManagementModel>>
    {
        private readonly IColumnManagementRepository column;
        public ColumnManagementListCommandHandler(IColumnManagementRepository _column)
        {
            column = _column;
        }

        public async Task<Pager<ColumnManagementModel>> Handle(ColumnManagementListCommand request, CancellationToken cancellationToken)
        {

            var list = await column.GetAllAsync();
            if (request.BuildingTypes == null)
            {
                request.BuildingTypes = 0;
            }
            if (request.BuildingTypes != 0)
            {
                list = list.Where(x => x.BuildingTypes == request.BuildingTypes).ToList();
            }
            if(!string.IsNullOrEmpty(request.BuildingName))
            {
                list=list.Where(x=>x.BuildingName.Contains(request.BuildingName)).ToList();
            }
            if (!string.IsNullOrEmpty(request.ResponsiblePerson))
            {
                list = list.Where(x => x.ResponsiblePerson.Contains(request.ResponsiblePerson)).ToList();
            }
            int totalCount = list.Count();
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);
            list = list.OrderByDescending(x => x.BuildingManagementId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();

            
            return new Pager<ColumnManagementModel>()
            {
                PageIndex = request.PageIndex,
                PageSize = request.PageSize,
                TotalCount = totalCount,
                PageCount = pageCount,
                resultData = list
            };
        }
        /// <summary>
        /// 栋舍返填
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<ColumnManagementModel>> Handle(ColumnManagementById request, CancellationToken cancellationToken)
        {
            var list = column.GetAllAsync().Result.Where(x => x.BuildingManagementId == request.BuildingManagementId);
            return list.ToList();
        }
    }
}
